package com.metalrain.alm.service;

import com.philips.lighting.model.PHBridge;
import com.philips.lighting.model.PHLight;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * This class Manages the lights
 */
public class LightManager {

    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    private final Executor lightThreadExecutor = Executors.newCachedThreadPool();
    private ScheduledFuture<?> future = null;


    public void start(PHBridge bridge) {
        future = executor.scheduleAtFixedRate(new LightTask(bridge),300,300, TimeUnit.MILLISECONDS);
    }

    public void stop() {
        if (future != null) {
            future.cancel(true);
        }
    }

    class LightTask extends TimerTask {
        final PHBridge bridge;
        long lastTimeMillis;

        public LightTask(PHBridge bridge) {
            this.bridge = bridge;
        }

        @Override
        public void run() {
            lastTimeMillis = System.currentTimeMillis();
            doColors();
        }

        private void doColors() {
                List<PHLight> allLights = (List<PHLight>) bridge.getResourceCache().getAllLights();
                for (final PHLight light : allLights) {
                    lightThreadExecutor.execute(LightRunnable.get(bridge, light));
                }

        }


    }


}
